import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/pages/information/station/view/status.dart';
import 'package:flutter_smart_heating/ui/src/pull_to_refresh.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';
import 'package:get/get.dart';

class InformationStationTemperRank extends StatefulWidget {
  const InformationStationTemperRank({super.key});

  @override
  State<InformationStationTemperRank> createState() =>
      _InformationStationTemperRankState();
}

class _InformationStationTemperRankState
    extends State<InformationStationTemperRank>
    with SingleTickerProviderStateMixin {
  late TabController tabController;

  @override
  void initState() {
    super.initState();
    tabController = TabController(length: 2, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('温度排行'),
        actions: const [
          UiRightMenuButtonGroup(),
        ],
      ),
      body: Column(
        children: [
          UiPanel(
            margin: const EdgeInsets.symmetric(
              horizontal: UiTheme.spacingX,
              vertical: UiTheme.toolbarSpacing,
            ),
            borderRadius: BorderRadius.circular(30),
            height: 40,
            child: TabBar(
              controller: tabController,
              isScrollable: false,
              dividerColor: Colors.transparent,
              indicatorSize: TabBarIndicatorSize.tab,
              splashBorderRadius: BorderRadius.circular(30),
              indicator: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(30),
                gradient: const LinearGradient(
                  colors: [
                    Color.fromARGB(255, 11, 232, 248),
                    Color.fromARGB(255, 33, 51, 243),
                  ],
                ),
              ),
              indicatorColor: Colors.black,
              labelColor: Colors.white,
              unselectedLabelColor:
                  UiTheme(context).matchColor(Colors.black, Colors.white),
              unselectedLabelStyle: const TextStyle(
                fontWeight: FontWeight.normal,
              ),
              labelStyle: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: UiTheme.fontSize.tabbarFontSize,
                color: Colors.red,
              ),
              tabs: const [
                Tab(
                  text: "回水温度排行",
                ),
                Tab(
                  text: "供水温度排行",
                ),
              ],
            ),
          ),
          Expanded(
            child: TabBarView(
              controller: tabController,
              children: const [
                InformationStationTemperRankView(type: 'in'),
                InformationStationTemperRankView(type: 'out'),
              ],
            ),
          ),
          const UiLineBreak(),
        ],
      ),
    );
  }
}

class InformationStationTemperRankView extends StatefulWidget {
  const InformationStationTemperRankView({super.key, required this.type});
  final String type;
  @override
  State<InformationStationTemperRankView> createState() =>
      _InformationStationTemperRankViewState();
}

class _InformationStationTemperRankViewState
    extends State<InformationStationTemperRankView>
    with AutomaticKeepAliveClientMixin {
  RefreshController refreshController = RefreshController();
  List<dynamic> list = [];
  bool loading = true;
  String sort = 'desc';
  @override
  void initState() {
    firstLoad();
    super.initState();
  }

  firstLoad() async {
    await 0.3.delay();
    fetchData();
  }

  fetchData() async {
    var res =
        await Http.instance.post('/api/information/station/temper_rank', data: {
      'type': widget.type,
      'sort': sort,
    });
    if (res.code == 1) {
      list = res.data;
    }
    loading = false;
    setState(() {});
    refreshController.refreshCompleted();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return loading
        ? const UiLoading()
        : Column(
            children: [
              Container(
                decoration: BoxDecoration(
                  color: Theme.of(context).scaffoldBackgroundColor,
                ),
                child: itemView(
                  index: '#',
                  company: '供暖企业',
                  station: '换热站',
                  value: '${widget.type == 'in' ? '回水' : '供水'}温度',
                  valueOnTap: () {
                    setState(() {
                      sort = sort == 'desc' ? 'asc' : 'desc';
                    });
                    Ui.toast(sort == 'desc' ? '已切换由高到低排序' : '已切换由低到高排序');
                    fetchData();
                  },
                  valueWidget: Container(
                    padding: const EdgeInsets.only(left: 2),
                    height: 18,
                    child: Column(
                      children: [
                        SizedBox(
                          height: 8,
                          child: Icon(
                            UiIcons.caret_up,
                            color: sort == 'asc' ? UiTheme.primary : null,
                            size: 10,
                          ),
                        ),
                        SizedBox(
                          height: 8,
                          child: Icon(
                            UiIcons.caret_down,
                            color: sort == 'desc' ? UiTheme.primary : null,
                            size: 10,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              const Divider(height: 0),
              Expanded(
                child: UiPushToRefresh(
                  controller: refreshController,
                  onRefresh: () {
                    fetchData();
                  },
                  child: list.isEmpty
                      ? const Center(
                          child: UiResult(),
                        )
                      : ListView.separated(
                          separatorBuilder: (context, index) =>
                              const Divider(height: 0),
                          itemBuilder: (context, index) {
                            var item = list[index];
                            return Container(
                              color: UiTheme(context).match(
                                light: index % 2 == 0 ? Colors.white : null,
                                dark: index % 2 == 0
                                    ? Colors.grey.withOpacity(0.1)
                                    : null,
                              ),
                              child: itemView(
                                index: index + 1,
                                company: item['company_name'],
                                companyOnTap: () {
                                  App.push(
                                      '/basic/company/detail?id=${item['company_id']}');
                                },
                                station: item['station_name'],
                                stationOnTap: () {
                                  App.push(
                                      '/basic/station/detail?id=${item['station_id']}');
                                },
                                value: item['value'] ?? '',
                                valueOnTap: () {
                                  StationStatusView.show(context,
                                      id: item['station_id']);
                                },
                              ),
                            );
                          },
                          itemCount: list.length,
                        ),
                ),
              ),
            ],
          );
  }

  Widget itemView({
    dynamic index,
    dynamic company,
    Function()? companyOnTap,
    dynamic station,
    Function()? stationOnTap,
    dynamic value,
    Widget? valueWidget,
    Function()? valueOnTap,
    double height = 45,
  }) {
    return Container(
      height: height,
      padding: const EdgeInsets.symmetric(
        horizontal: UiTheme.spacingX,
      ),
      child: Row(
        children: [
          SizedBox(
            width: 30,
            child: Text(
              '$index',
              textAlign: TextAlign.center,
            ),
          ),
          UiTap(
            onTap: companyOnTap,
            child: SizedBox(
              width: 90,
              height: height,
              child: Center(
                child: Text(
                  '$company',
                  textAlign: TextAlign.center,
                ),
              ),
            ),
          ),
          Expanded(
            child: UiTap(
              onTap: stationOnTap,
              child: SizedBox(
                height: height,
                child: Center(
                  child: Text(
                    '$station',
                    overflow: TextOverflow.ellipsis,
                    textAlign: TextAlign.center,
                  ),
                ),
              ),
            ),
          ),
          UiTap(
            onTap: valueOnTap,
            child: SizedBox(
              width: 90,
              height: height,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '$value',
                    textAlign: TextAlign.center,
                  ),
                  if (valueWidget != null) valueWidget
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
